import os
import csv

# 使用写入模式打开当前脚本目录下test1.csv文件
f = open(os.path.join(os.path.dirname(__file__), 'tes1.csv'), 'w', 
        newline='', encoding='utf-8')

with f:
    fnames = ['姓名', '年龄']
    writer = csv.DictWriter(f, fieldnames=fnames)
    writer.writeheader()  # 写入fnames
    writer.writerow({'姓名': '张三', '年龄': 23})
    writer.writerow({'姓名': '李四', '年龄': 24})
    writer.writerow({'姓名': '王五', '年龄': 18})
